package com.lingxu.base.common.util;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

public class PersonDownCache {

    private static PersonDownCache cache;

    // 缓存过期时间
    private final Cache<String, Integer> downProcessCache = CacheBuilder.newBuilder().maximumSize(1000)
            .expireAfterWrite(10, TimeUnit.MINUTES).build();

    public void refreshLocalCahe() {
        downProcessCache.invalidateAll();
    }

    /**
     * 根据健值获取缓存
     * @param key
     * @return
     */
    public Integer getProcess(String key) {
        Integer process = downProcessCache.getIfPresent(key);
        if (process == null) {
            synchronized (this) {
                process = downProcessCache.getIfPresent(key);
                if (process == null) {
                    process = 0;
                    downProcessCache.put(key, process);
                }
            }
        }
        return process;
    }

    /**
     * 根据健值获取设置缓存
     * @param key
     * @return
     */
    public void setProcess(String key, Integer process) {
        downProcessCache.put(key, process);
    }

    /**
     * 获取实例
     * @return
     */
    public static PersonDownCache getInstance() {
        if (cache == null) {
            cache = new PersonDownCache();
        }
        return cache;
    }

    /**
     * 根据健值刷新缓存
     */
    public void refreshCacheByKey(String key) {
        if (StringUtils.isNotEmpty(key)) {
            Integer cache = 0;
            downProcessCache.put(key, cache);
        }
    }

    /**
     * 使所有缓存失效
     */
    public void refresh() {
        refreshLocalCahe();
    }
}
